from flask import render_template, flash, redirect, url_for
from win32com.client import Dispatch,DispatchEx, constants, gencache
import pythoncom

from . import home_bp
from myapp.utils import redirect_back

@home_bp.route('/')
def index():
    # return render_template('starter.html')      # 采用adminLTE基模板
    return render_template('home/index.html')      # 采用原有的bootstrap基模板

@home_bp.route('/about')
def about():
    flash('消息：自我介绍。')
    return render_template('home/about.html')

@home_bp.route('/settings')
def settings():
    return render_template('home/settings.html')

GL_WORDAPP = None
G_DOC = None
GL_EXCELAPP = None
G_SHEET = None
G_FLAG = 1

@home_bp.route('/open_word')
def open_word():
    """打开Word文件"""
    sourcepath = r"E:\openWord.docx"
    # import pythoncom
    pythoncom.CoInitialize()
    global GL_WORDAPP
    GL_WORDAPP = Dispatch("Word.Application")
    GL_WORDAPP.Visible =1
    # wordDoc = wordApp.Documents.Open(sourcepath)
    global G_DOC
    G_DOC = GL_WORDAPP.Documents.Open(r"E:\openWord.docx")
    global G_FLAG
    if G_FLAG == 0:
        G_DOC.Close()
        GL_WORDAPP.Quit()
        del(GL_WORDAPP)
    return redirect_back()

@home_bp.route('/close_word')
def close_word():
    """关闭Word文件"""
    global G_FLAG
    G_FLAG = 0
    '''
    global G_DOC
    global GL_WORDAPP
    # G_DOC.Save()
    G_DOC.Close()
    pythoncom.CoUninitialize()
    GL_WORDAPP.Quit()
    del(GL_WORDAPP)
    return redirect_back()
    '''

@home_bp.route('/open_excel')
def open_excel():
    """打开Excel文件"""
    import pythoncom
    pythoncom.CoInitialize()
    global GL_EXCELAPP
    GL_EXCELAPP = Dispatch("Excel.Application")
    GL_EXCELAPP.Visible = 1
    global G_SHEET
    G_SHEET = GL_EXCELAPP.Workbooks.Open(r"E:\openExcel.xlsx")
    # excelSheet.Close()
    # excelApp.Quit()
    # del(excelApp)
    return redirect_back()



@home_bp.route('/close_excel')
def close_excel():
    """关闭excel文件"""

    G_SHEET.Close()
    GL_EXCELAPP.Quit()
    del(GL_EXCELAPP)
    return redirect_back()